package com.itheima.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MybatisUtil {

    private static SqlSessionFactory sqlSessionFactory = null;

    //保证SqlSessionFactory仅仅创建一次
    static {
        try {
            //读取配置文件
            InputStream stream = Resources.getResourceAsStream("SqlMapConfig.xml");
            //创建SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取sqlSession
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }

    //提交事务 关闭sqlSession
    public static void close(SqlSession sqlSession) {
        if (sqlSession != null) {
            //提交事务
            sqlSession.commit();
            //释放资源
            sqlSession.close();
        }
    }
}
